package com.example.installdemo;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_UNKNOWN_APP_SOURCES = 1001;
    private static final String APK_PATH = "/storage/emulated/0/ceshiapp.apk";
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 101;

    // 检查并请求权限
    private boolean checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                requestPermissions(new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                }, REQUEST_CODE_STORAGE_PERMISSION);
                return false;
            }
        }
        return true; // 已经有权限
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE_STORAGE_PERMISSION) {
            boolean granted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    granted = false;
                    break;
                }
            }

            if (granted) {
                installApk(); // 权限允许，执行安装
            } else {
                Toast.makeText(this, "存储权限未授予，无法安装APK", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnInstall = findViewById(R.id.btnInstall);
        btnInstall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPermissionAndInstall();
            }
        });
    }

    /**
     * 检查权限并安装APK
     */
    private void checkPermissionAndInstall() {
        File apkFile = new File(APK_PATH);
        if (!apkFile.exists()) {
            Toast.makeText(this, "APK文件不存在，请检查路径", Toast.LENGTH_SHORT).show();
            return;
        }

//        if (!checkStoragePermission()) {
//            // 权限请求中，等回调
//            return;
//        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (getPackageManager().canRequestPackageInstalls()) {
                installApk();
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_CODE_UNKNOWN_APP_SOURCES);
            }
        } else {
            installApk();
        }
    }


    /**
     * 处理权限请求结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_UNKNOWN_APP_SOURCES) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (getPackageManager().canRequestPackageInstalls()) {
                    installApk();
                } else {
                    Toast.makeText(this, "未获得安装权限，无法安装应用", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    /**
     * 执行APK安装
     */
    private void installApk() {
        File apkFile = new File(APK_PATH);
        if (!apkFile.exists()) {
            Toast.makeText(this, "APK文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }

        Uri apkUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            apkUri = FileProvider.getUriForFile(
                    this,
                    "com.huanglong.explorer.fileprovider",
                    apkFile
            );
        } else {
            apkUri = Uri.fromFile(apkFile);
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);

        // 👇 关键：授权系统安装器访问 URI
        grantUriPermission("com.android.packageinstaller", apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

        try {
            startActivity(intent);
        } catch (Exception e) {
            Log.e("InstallDemo", "安装失败: " + e.getMessage(), e);
            Toast.makeText(this, "无法启动安装程序", Toast.LENGTH_SHORT).show();
        }
    }
    public boolean isAPKValid(Context context, String apkPath) {
        File apkFile = new File(apkPath);
        if (!apkFile.exists()) {
            Log.e("InstallDemo", "APK文件不存在: " + apkPath);
            return false;
        }

        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                // Android 13+ 新API
                packageInfo = pm.getPackageArchiveInfo(
                        apkPath,
                        PackageManager.PackageInfoFlags.of(PackageManager.GET_ACTIVITIES)
                );
            } else {
                // 旧API
                packageInfo = pm.getPackageArchiveInfo(apkPath, PackageManager.GET_ACTIVITIES);
            }
            return packageInfo != null;
        } catch (Exception e) {
            Log.e("InstallDemo", "APK解析失败: " + e.getMessage(), e);
            return false;
        }
    }

}